/**
 * 定时轮询工具
 */
const TimedPollingUtil = {
    /**
     * 请求地址
     */
    url: null,
    /**
     * 请求参数
     */
    parameters: null,
    /**
     * 轮询时间
     */
    pollingTime: 5000,
    /**
     * ajax请求等待时间
     */
    ajaxTimeout: 10000,
    /**
     * 轮询对象
     */
    pollingObj: null,
    /**
     * 请求是否结束
     */
    endOfRequest: true,
    /**
     * 回调函数
     */
    callback: null,
    /**
     * 初始化启动
     * @param url
     * @param parameters
     * @param callback
     * @param pollingTime
     * @param ajaxTimeout
     */
    initAjax(url,parameters,callback,pollingTime,ajaxTimeout){
        if(!url){
            console.error("请传入请求地址！")
            return
        }
        const thas = this
        // 参数赋值
        this.url = url
        if(parameters){
            thas.parameters = parameters
        }
        if(pollingTime){
            thas.pollingTime = pollingTime
        }
        if(ajaxTimeout){
            thas.pollingTime = ajaxTimeout
        }
        if(callback){
            thas.callback = callback
        }else {
            thas.callback = function (ret){
                console.log("回调参数",ret)
            }
        }
        // 开始查询
        if(thas.pollingObj){
            window.clearInterval(thas.pollingObj)
        }
        thas.pollingObj = window.setInterval(function (){
            if (thas.endOfRequest){
                thas.request(thas)
            } else {
                console.log("上次请求还未结束！")
            }
        },thas.pollingTime)
    },
    /**
     * 关闭
     */
    clear(){
        if(!this.pollingObj){
            return
        }
        window.clearInterval(this.pollingObj)
        this.pollingObj = null
        console.log("轮询关闭！")
    },
    /**
     * 请求
     * @param thas
     */
    request(thas){
        thas.endOfRequest = false
        $.ajax({
            url: thas.url,
            type:'post',
            dataType: 'json',
            data: thas.parameters,
            timeout: thas.ajaxTimeout,
            success: thas.callback,
            error:function(){
                console.log("消息查询异常！")
            }
        }).always(function (){
            thas.endOfRequest = true
        })
    }
}